<template>
  <div class="page">
    <div class="page-wrapper">
      <!-- 标题 -->
      <div class="header">
        <span></span>
        {{
          route.currentRoute.value.query.id &&
          route.currentRoute.value.query.mark == 'pending'
            ? '审核订单'
            : route.currentRoute.value.query.id
            ? '修改订单'
            : '修改客户'
        }}
      </div>
      <!-- 折叠面板 -->
      <el-collapse v-model="activeNames">
        <!-- 客户信息 -->
        <collapse-item name="1" title="客户信息">
          <!-- 新增订单、订单详情-->
          <form-group
            :list="baseOrder"
            :options="option"
            :value="objValue"
            label-width="200px"
            ref="baseOrder"
            :disabled="disabledT"
            v-if="route.currentRoute.value.query.id"
            @onchangeT="onchangeT"
          />

          <form-group
            :list="base"
            :options="option"
            :value="objValue"
            label-width="200px"
            :disabled="disabledT"
            ref="base"
            v-else
          />
        </collapse-item>
        <!-- 代账公司专属信息 -->
        <collapse-item
          v-if="objValue.custype === '1' && !route.currentRoute.value.query.id"
          name="2"
          title="代账公司专属信息"
        >
          <form-group
            :list="agency"
            :options="option"
            :value="objValue"
            label-width="200px"
            ref="agency"
            :disabled="disabledT"
          />
        </collapse-item>
        <!-- 联系方式 -->
        <collapse-item
          name="3"
          title="联系方式"
          v-if="!route.currentRoute.value.query.id"
        >
          <div class="table">
            <div class="table-label">联系方式</div>
            <el-table class="table-content" :data="lxfs" stripe border>
              <el-table-column prop="label" align="center" width="100">
                <template #default="scoped">
                  <span v-if="scoped.row.index === 1" style="color: red"
                    >*</span
                  >
                  联系人{{ scoped.row.index }}
                </template>
              </el-table-column>
              <el-table-column
                prop="name"
                label="姓名"
                align="center"
                width="180"
              >
                <template #default="scoped">
                  <el-input
                    v-if="scoped.row.index == 3"
                    placeholder="姓名"
                    v-model="scoped.row.name"
                    disabled
                  ></el-input>
                  <el-input
                    v-else
                    placeholder="姓名"
                    v-model="scoped.row.name"
                    :disabled="disabledT"
                  >
                  </el-input>
                </template>
              </el-table-column>
              <el-table-column prop="work" align="center" label="职务">
                <template #default="scoped">
                  <el-input
                    v-if="scoped.row.index != 1"
                    placeholder="职务"
                    v-model="scoped.row.work"
                    disabled
                  ></el-input>
                  <el-input
                    v-else
                    placeholder="职务"
                    v-model="scoped.row.work"
                    :disabled="disabledT"
                  >
                  </el-input>
                </template>
              </el-table-column>
              <el-table-column prop="phone" align="center" label="联系电话">
                <template #default="scoped">
                  <el-input
                    placeholder="联系电话"
                    v-model="scoped.row.phone"
                    :disabled="disabledT"
                  >
                  </el-input>
                </template>
              </el-table-column>
              <el-table-column prop="operate" align="center" label="操作">
                <template #default="scoped">
                  <el-button
                    v-if="scoped.row.index !== 1"
                    link
                    @click="delLxfs(scoped.row.index)"
                    :disabled="disabledT"
                    >删除</el-button
                  >
                  <el-button
                    v-else
                    :disabled="lxfs.length === 3 || disabledT"
                    link
                    @click="addLxfs"
                    >添加</el-button
                  >
                </template>
              </el-table-column>
            </el-table>
          </div>

          <form-group
            :list="contact"
            :options="option"
            :value="objValue"
            label-width="200px"
            ref="contact"
            :disabled="disabledT"
          />
        </collapse-item>
        <!-- 开票信息 -->
        <collapse-item
          name="4"
          v-if="route.currentRoute.value.query.id"
          title="开票信息"
        >
          <form-group
            :list="invoice"
            :options="option"
            :value="objValue"
            label-width="200px"
            ref="invoice"
          />
        </collapse-item>
        <!-- 其他信息 -->
        <collapse-item
          name="5"
          v-if="route.currentRoute.value.query.id"
          title="其他信息"
        >
          <form-group
            :list="other"
            :options="option"
            :value="objValue"
            label-width="200px"
            :disabled="disabledT"
          />
        </collapse-item>
        <!-- 合同信息 -->
        <collapse-item
          name="6"
          v-if="route.currentRoute.value.query.id"
          title="合同信息"
        >
          <el-button
            type="primary"
            size="small"
            icon="Plus"
            @click="addAgreement"
            >新增</el-button
          >
          <el-button
            type="danger"
            size="small"
            icon="Delete"
            @click="deleteAgreements"
            :disabled="multiple"
            >删除</el-button
          >
          <el-table
            :data="objValue.fileList"
            border
            style="width: 100%; margin-top: 10px"
            @selection-change="handleSelectionChangeTwo"
          >
            <el-table-column
              type="selection"
              align="center"
              width="55"
            ></el-table-column>
            <el-table-column
              type="index"
              label="合同序号"
              width="100"
              align="center"
            />

            <el-table-column prop="fileName" label="合同名称" align="center" />
            <!-- <el-table-column prop="" label="操作" align="center"
              ><template #default="scoped">
                <el-button
                  size="mini"
                  type="text"
                  @click="fetchFile(scoped.row.url)"
                  >下载</el-button
                >
              </template>
            </el-table-column> -->
          </el-table>
        </collapse-item>
        <!-- 订单信息 -->
        <collapse-item
          name="7"
          v-if="route.currentRoute.value.query.id"
          title="订单信息"
        >
          <form-group
            :list="ordernoT"
            :value="ordernoValue"
            label-width="80px"
            ref="ordernoT"
            :disabled="disabledT"
          />
          <el-button
            type="primary"
            size="small"
            icon="Plus"
            @click="addGoods"
            :disabled="disabledT"
          >
            新增物品</el-button
          >
          <el-button
            type="danger"
            size="small"
            icon="Delete"
            @click="deleteGoods"
            :disabled="multiple2"
            >删除物品</el-button
          >
          <el-button
            type="success"
            size="small"
            icon="Edit"
            @click="updateGoods"
            :disabled="single"
          >
            修改物品</el-button
          >
          <el-table
            :data="objValue.orderlineList"
            border
            style="width: 100%; margin-top: 10px"
            @selection-change="handleSelectionChange"
          >
            <el-table-column
              type="selection"
              align="center"
              width="55"
            ></el-table-column>
            <el-table-column
              type="index"
              label="序号"
              width="50"
              align="center"
            />

            <el-table-column prop="matId" label="物品编码" align="center" />
            <el-table-column prop="matName" label="物品名称" align="center" />
            <el-table-column prop="matType" label="规格/型号" align="center" />
            <el-table-column prop="matNum" label="数量" align="center" />
            <el-table-column prop="unitName" label="单位" align="center" />
            <el-table-column prop="unitPrice" label="单价" align="center" />
            <el-table-column prop="amount" label="总金额" align="center" />
            <el-table-column
              prop="collectAmount"
              label="回款金额"
              align="center"
            />
            <el-table-column
              prop="collectPercent"
              label="回款金额百分比"
              align="center"
            />
            <el-table-column prop="remark" label="备注" align="center" />
          </el-table>
        </collapse-item>
      </el-collapse>
      <!-- 底部按钮 -->
      <div class="footer">
        <div>
          <el-button
            v-if="route.currentRoute.value.query.mark == 'pending'"
            v-loading="loadingCheck"
            type="primary"
            @click="handleCheck(2)"
          >
            审核通过
          </el-button>

          <el-button
            v-if="route.currentRoute.value.query.mark == 'pending'"
            type="danger"
            @click="handleCheck(7)"
          >
            审核不通过
          </el-button>
        </div>

        <div>
          <el-button
            v-if="
              route.currentRoute.value.query.mark == 'pending' ||
              route.currentRoute.value.query.mark == 'audited'
            "
            v-loading="loadingCopy"
            type="primary"
            @click="handleSubmit(1)"
          >
            复制订单
          </el-button>

          <el-button
            v-if="isDisabled"
            v-loading="loadingCancel"
            @click="handleCancel"
            type="danger"
          >
            作废订单
          </el-button>

          <el-button
            v-if="route.currentRoute.value.query.mark == 'audited'"
            v-loading="loadingRedCreate"
            @click="handleSubmit(-1)"
            type="danger"
          >
            红字订单
          </el-button>
        </div>
        <div>
          <el-button
            v-if="route.currentRoute.value.query.id"
            v-loading="loading"
            type="primary"
            @click="handleSubmit"
          >
            保存
          </el-button>

          <el-button
            v-if="!route.currentRoute.value.query.id"
            v-loading="loading"
            type="primary"
            @click="handleSubmit"
          >
            提交
          </el-button>
          <el-button plain @click="handleBack"> 返回 </el-button>
        </div>
      </div>
    </div>
    <!-- 新增订单信息 -->
    <!-- <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="50%"> -->
    <el-dialog
      :title="dialogTitle"
      v-model="dialogVisible"
      width="50%"
      append-to-body
    >
      <el-tabs v-model="activeName">
        <el-tab-pane label="单产品" name="first">
          <el-form
            :model="formT"
            ref="queryForm"
            :rules="rules"
            :inline="true"
            label-width="80px"
          >
            <el-row>
              <el-form-item label="物品编码" prop="matId">
                <el-select
                  filterable
                  v-model="formT.matId"
                  placeholder="请选择"
                  @change="matCodeChange"
                >
                  <el-option
                    v-for="item in matCodeOptions"
                    :key="item.matCode"
                    :label="item.matCode"
                    :value="item.matCode"
                  >
                  </el-option>
                </el-select>
              </el-form-item>
              <el-row> </el-row>
              <el-form-item label="物品名称" prop="matName">
                <el-select
                  filterable
                  v-model="formT.matName"
                  placeholder="请选择"
                  @change="matNameChange"
                >
                  <el-option
                    v-for="item in matCodeOptions"
                    :key="item.matCode"
                    :label="item.matName"
                    :value="item.matName"
                  >
                  </el-option>
                </el-select>
              </el-form-item>
              <el-row> </el-row>
              <el-form-item label="规格/型号" prop="matType">
                <el-input v-model="formT.matType" placeholder="" disabled />
              </el-form-item>
              <el-row> </el-row>
              <el-form-item label="单位" prop="unitName">
                <el-input v-model="formT.unitName" placeholder="" disabled />
              </el-form-item>
              <el-row> </el-row>
              <el-form-item label="数量" prop="matNum">
                <el-input
                  v-model="formT.matNum"
                  placeholder="请输入数量"
                  @input="onInput(0)"
                />
              </el-form-item>
              <el-row> </el-row>
              <el-form-item label="单价" prop="unitPrice">
                <el-input
                  v-model="formT.unitPrice"
                  placeholder="请输入单价"
                  @input="onInput(1)"
                />
              </el-form-item>
              <el-row> </el-row>
              <el-form-item label="总金额" prop="amount">
                <el-input v-model="formT.amount" placeholder="请输入总金额" />
              </el-form-item>
              <el-row> </el-row>
              <el-form-item label="备注" prop="remark">
                <el-input
                  v-model="formT.rerequestUploadmark"
                  type="textarea"
                  placeholder="请输入备注"
                />
              </el-form-item>
            </el-row>
            <el-row>
              <el-form-item style="margin-left: 80px">
                <el-button @click="dialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="onConfirm">确 定</el-button>
              </el-form-item>
            </el-row>
          </el-form>
        </el-tab-pane>
        <el-tab-pane label="套餐产品" name="second">
          <el-form
            :model="formMeal"
            ref="mealForm"
            :rules="ruleMeal"
            :inline="true"
            label-width="80px"
          >
            <el-form-item label="套餐名称" prop="mealName">
              <el-select
                filterable
                v-model="formMeal.mealName"
                placeholder="请选择"
                @change="mealNameChange"
              >
                <el-option
                  v-for="item in tableList"
                  :key="item.id"
                  :label="item.mealName"
                  :value="item.id"
                >
                </el-option>
              </el-select>
            </el-form-item>

            <el-form-item label="套餐价格" prop="amount">
              <el-input v-model="formMeal.amount" placeholder="" disabled />
            </el-form-item>

            <el-form-item label="套餐内容" prop="amount">
              <el-table show-summary :data="mealLines" border>
                <el-table-column
                  prop="matName"
                  label="商品名称"
                  align="center"
                />
                <el-table-column prop="spec" label="商品规格" align="center" />
                <el-table-column prop="unit" label="单位" align="center" />
                <el-table-column prop="matNum" label="数量" align="center" />
                <el-table-column prop="price" label="单价" align="center" />
                <el-table-column prop="amount" label="金额" align="center" />
              </el-table>
            </el-form-item>

            <el-form-item style="margin-left: 80px">
              <el-button @click="dialogVisible = false">取 消</el-button>
              <el-button type="primary" @click="onConfirmMeal">确 定</el-button>
            </el-form-item>
          </el-form>
        </el-tab-pane>
      </el-tabs>
    </el-dialog>

    <!-- 新增合同弹出框 -->
    <!-- <el-dialog :title="agreementDialogTitle" :visible.sync="agreementDialogVisible" width="35%"> -->
    <el-dialog
      :title="agreementDialogTitle"
      v-model="agreementDialogVisible"
      width="500px"
      append-to-body
    >
      <el-form
        :model="agreementForm"
        ref="agreementFormRef"
        :rules="agreementRules"
        :inline="true"
        label-width="80px"
      >
        <el-form-item label="合同名称" prop="fileName">
          <el-input
            v-model="agreementForm.fileName"
            placeholder="请输入合同名称"
          />
        </el-form-item>
        <el-form-item label="上传">
          <el-upload
            class="item item-value"
            action="#"
            :limit="1"
            :http-request="file => requestUpload(file)"
          >
            <el-button size="small" type="primary">
              选择
              <i class="Upload"></i>
            </el-button>
          </el-upload>
        </el-form-item>
      </el-form>

      <span class="dialog-footer">
        <el-button @click="agreementDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="agreementOnConfirm">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script setup name="changeOrder">
import { listTable, getMealLineList } from '@/api/erp/packageManagement'
import {
  cancelOrder,
  copyOrder,
  createRedOrder,
  checkOrder,
  syncOrder,
  fetchCityList,
  fetchRegionList,
  fetchCustomerTaxBureauList,
  fetchAgencyList,
  fetchManagerList,
  fetchCustomerDetail,
  updateCompany,
  detailOrder,
  updateOrder,
  addOrder,
  customerListSelect
} from '@/api/order/order'
import FormGroup from '@/views/erp/orderManagement/modules/FormGroup'
import CollapseItem from '@/views/erp/orderManagement/modules/CollapseItem'
import { fileUpload } from '@/api/order/order'
import { materialList } from '@/api/erp/orderManagement'
import { getCurrentInstance, nextTick, reactive, toRefs } from 'vue'
import { useRouter } from 'vue-router'

const { proxy } = getCurrentInstance()
const route = useRouter()
const router = useRouter()
const data = reactive({
  formOrderNo: {},
  disabledT: false,
  isDisabled: false,
  // 套餐内容表数据
  mealLines: [],
  // 表数据
  tableList: [],
  matCodeOptions: [],
  agreementRules: {
    fileName: [{ required: true, message: '请输入合同名称', trigger: 'blur' }]
  },
  rules: {
    matId: [{ required: true, message: '请选择物料编码', trigger: 'blur' }],
    amount: [{ required: true, message: '请输入总金额', trigger: 'blur' }]
  },
  formMeal: {
    mealName: '',
    amount: ''
  },
  ruleMeal: {
    mealName: [{ required: true, message: '请选择套餐名称', trigger: 'blur' }]
  },
  agreementForm: { fileName: null, url: null },
  uploadQueryOptions: [],
  dialogVisible: false,
  agreementDialogVisible: false,
  agreementDialogTitle: '',
  dialogTitle: '',
  // 非单个禁用
  single: true,
  // 非多个禁用
  multiple: true,
  multiple2: true,
  loading: false,
  loadingCancel: false,
  loadingCopy: false,
  loadingRedCreate: false,
  loadingNoCheck: false,
  loadingCheck: false,
  activeNames: undefined,
  base: [
    [
      {
        label: '纳税人识别号',
        id: 'ceTaxcode',
        rules: () => [
          {
            required: true,
            message: '请输入纳税人识别号',
            trigger: 'blur'
          }
        ]
      },
      {
        label: '企业名称',
        id: 'ceEtpname',
        rules: () => [
          { required: true, message: '请输入企业名称', trigger: 'blur' }
        ]
      },
      {
        label: '企业性质',
        id: 'cusScaleId',
        type: 'select',
        rules: () => [
          { required: true, message: '请选择所属地区', trigger: 'blur' }
        ]
      }
    ],
    [
      {
        label: '所属地区',
        id: 'citycodes',
        type: 'select',
        mapper: ['codevalue', 'codename'],
        rules: () => [
          { required: true, message: '请选择所属地区', trigger: 'blur' }
        ]
      },
      {
        label: '所属片区',
        id: 'region',
        type: 'select',
        mapper: ['wdbm', 'wdname'],
        rules: () => [
          { required: true, message: '请选择所属片区', trigger: 'blur' }
        ]
      },
      {
        label: '所属税务机关',
        id: 'ceTaxbureaid',
        type: 'select',
        mapper: ['taxBureaId', 'taxBureaName'],
        rules: () => [
          {
            required: true,
            message: '请选择所属税务机关',
            trigger: 'blur'
          }
        ]
      }
    ],
    [
      {
        label: '客户经理',
        id: 'khjlid',
        type: 'select',
        mapper: ['khjlId', 'khjlName'],
        rules: () => [
          { required: true, message: '请选择客户经理', trigger: 'blur' }
        ]
      },
      {
        label: '客户类别',
        id: 'custype',
        type: 'select',
        rules: () => [
          { required: true, message: '请选择客户类别', trigger: 'blur' }
        ]
      },
      {
        label: '注册资本',
        id: 'ceRegmoney',
        rules: () => [
          { required: true, message: '请输入注册资本', trigger: 'blur' }
        ]
      }
    ]
  ],
  baseOrder: [
    [
      {
        label: '企业名称',
        id: 'ceEtpname',
        type: 'select',
        mapper: ['ceTaxcode', 'ceEtpname'],
        change: true
        // rules: () => [
        //   { required: true, message: "请输入企业名称", trigger: "blur" },
        // ],
      },
      {
        label: '纳税人识别号',
        id: 'ceTaxcode',
        rules: () => [
          {
            required: true,
            message: '请输入纳税人识别号',
            trigger: 'blur'
          }
        ]
      },

      {
        label: '联系人',
        id: 'contactName'
      }
    ],
    [
      {
        label: '联系方式',
        id: 'contactPhone',
        span: 8
      },
      {
        label: '联系地址',
        id: 'contactAddress',
        span: 8
      }
    ]
  ],
  contact: [
    [
      {
        label: '企业地址',
        id: 'ceOfficeaddr',
        span: 8,
        rules: () => [
          { required: true, message: '请输入企业地址', trigger: 'blur' }
        ]
      }
    ]
  ],
  agency: [
    [
      {
        label: '授权码',
        id: 'sqm',
        rules: () => [
          { required: true, message: '请输入授权码', trigger: 'blur' }
        ]
      },
      {
        label: '星级授牌时间',
        id: 'spsj',
        type: 'date',
        rules: () => [
          {
            required: true,
            message: '请选择星级授权时间',
            trigger: 'blur'
          }
        ]
      },
      {
        label: '星级授牌到期时间',
        id: 'spdqsj',
        type: 'date',
        rules: () => [
          {
            required: true,
            message: '请选择星级授牌到期时间',
            trigger: 'blur'
          }
        ]
      }
    ],
    [
      {
        label: '代账公司每户分润金额',
        id: 'frje',
        rules: () => [
          {
            required: true,
            message: '请选择代账公司每户分润金额',
            trigger: 'blur'
          }
        ]
      },
      {
        label: '代账公司每户收取金额',
        id: 'sqje',
        rules: () => [
          {
            required: true,
            message: '请选择代账公司每户收取金额',
            trigger: 'blur'
          }
        ]
      },
      { label: '代账公司合同上传', id: 'htxy', type: 'upload' }
    ],
    [
      {
        label: '代账公司授牌照片上传',
        id: 'spzp',
        type: 'upload',
        span: 8
      }
    ]
  ],
  ordernoValue: { orderNo: '' },
  ordernoT: [
    [
      {
        label: '订单号',
        id: 'orderNo',
        type: 'input',
        span: 8,
        show: val => {
          return route.currentRoute.value.query.type == '1' ? true : false
        },
        rules: () => [
          { required: true, message: '请输入订单号', trigger: 'blur' }
        ]
      }
    ]
  ],
  invoice: [
    [
      { label: '发票类型', id: 'billType', type: 'select' },
      // {
      //   label: "销售人员",
      //   id: "salespersonId",
      //   type: "input",
      //   rules: () => [
      //     {
      //       required: true,
      //       message: "请填写销售人员",
      //       trigger: "blur",
      //     },
      //   ],
      // },
      { label: '发票邮箱', id: 'billEmail' }
    ],
    [
      {
        label: '银行名称',
        id: 'bank',
        span: 8,
        show: val => {
          return val.billType == '3' ? true : false
        },
        rules: val => {
          return val.billType === '3'
            ? [
                {
                  required: true,
                  message: '请输入银行名称',
                  trigger: 'blur'
                }
              ]
            : []
        }
      },
      {
        label: '银行卡号',
        id: 'bankAccount',
        span: 8,
        show: val => {
          return val.billType == '3' ? true : false
        },
        rules: val => {
          return val.billType === '3'
            ? [
                {
                  required: true,
                  message: '请输入银行账号',
                  trigger: 'blur'
                }
              ]
            : []
        }
      }
    ]
  ],
  other: [
    [
      { label: '所属业务板块', id: 'ssywbk', type: 'select' },
      { label: '业务流程', id: 'ywlc', type: 'select' },
      { label: '项目型业务关联', id: 'ck', type: 'select' }
    ],
    [],
    [
      { label: '是否红字', id: 'sfhz', type: 'select', span: 8 },
      { label: '单据类型', id: 'djlx', type: 'select', span: 8 }

      // { label: "合同", id: "ht", type: "upload" },
    ],
    [
      {
        label: '销售人员',
        id: 'salespersonId',
        type: 'select',
        mapper: ['khjlId', 'khjlName'],
        span: 8
      },
      { label: '备注', id: 'remark', span: 16 }
    ]
    // [{ label: "备注", id: "remark", span: 16 }],
  ],
  objValue: {
    custype: null
  },
  activeName: 'first',
  formT: {
    matId: '',
    amount: '',
    unitPrice: '',
    matNum: '',
    unitName: '',
    matType: '',
    matName: '',
    remark: ''
  },
  option: {
    salespersonId: [], //销售人员
    ceEtpname: [],
    cusScaleId: [
      { label: '一般纳税人', value: '0' },
      { label: '小规模纳税人', value: '1' },
      { label: '点下户', value: '2' },
      { label: '非纳税人', value: '3' }
    ],
    custype: [
      { label: '一般产品客户', value: '0' },
      { label: '代账公司', value: '1' },
      { label: '重点客户', value: '2' }
    ],
    xj: [
      { label: '一星', value: '1' },
      { label: '二星', value: '2' },
      { label: '三星', value: '3' },
      { label: '四星', value: '4' },
      { label: '五星', value: '5' }
    ],
    sfhz: [
      { label: '蓝字', value: '1' },
      { label: '红字', value: '2' }
    ],
    djlx: [
      { label: '通用', value: '1' },
      { label: '专用', value: '2' }
    ],
    ywlc: [
      { label: '普通流程', value: '1' },
      { label: '服务费流程', value: '2' },
      { label: '项目型业务流程', value: '3' }
    ],
    ssywbk: [
      { label: '金税', value: '1' },
      { label: '政务', value: '2' },
      { label: '金融', value: '3' }
    ],
    billType: [
      { label: '普通发票', value: '1' },
      { label: '电子发票', value: '2' },
      { label: '专用发票', value: '3' }
    ],
    khjlid: [],
    dzjgId: [],
    ceTaxbureaid: [],
    citycodes: [],
    region: [],
    classify: []
  },
  lxfs: [{ index: 1, name: '', work: '', phone: '' }],
  matCodes: '',
  urls: ''
})
const {
  urls,
  matCodes,
  formOrderNo,
  disabledT,
  isDisabled,
  // 套餐内容表数据
  mealLines,
  // 表数据
  tableList,
  matCodeOptions,
  agreementRules,
  rules,
  formMeal,
  ruleMeal,
  agreementForm,
  uploadQueryOptions,
  dialogVisible,
  agreementDialogVisible,
  agreementDialogTitle,
  dialogTitle,
  // 非单个禁用
  single,
  // 非多个禁用
  multiple,
  multiple2,
  loading,
  loadingCancel,
  loadingCopy,
  loadingRedCreate,
  loadingNoCheck,
  loadingCheck,
  activeNames,
  base,
  baseOrder,
  contact,
  agency,
  ordernoValue,
  ordernoT,
  invoice,
  other,
  value,
  activeName,
  formT,
  option,
  lxfs,
  objValue
} = toRefs(data)

async function init() {
  console.log('route===', route)
  // 两个入口：1.客户档案 2.订单管理
  activeNames.value = route.currentRoute.value.query.id
    ? ['1', '2', '3', '4', '5', '6', '7']
    : ['1', '2', '3']

  if (route.currentRoute.value.query.checkStatus == '2') {
    disabledT.value = true
  } else if (route.currentRoute.value.query.mark == 'audited') {
    disabledT.value = true
  } else {
    disabledT.value = false
  }
  await getDetail()
  objValue.value.ceTaxcode = objValue.value.custTaxcode
  if (objValue.value.orderNo) {
    if (objValue.value.sfhz === '1') {
      ordernoValue.value.orderNo = objValue.value.orderNo + '-HZ'
    } else {
      ordernoValue.value.orderNo = objValue.value.orderNo
    }
  }
  objValue.value.classifyName =
    objValue.value.classifyname3 ||
    objValue.value.classifyname2 ||
    objValue.value.classifyname1
  lxfs.value[0].name = objValue.value.ceContactname
  lxfs.value[0].phone = objValue.value.ceContactmobileOne
  lxfs.value[0].work = objValue.value.linkwork

  if (
    objValue.value.ceContactname2 ||
    objValue.value.ceContactmobile2 ||
    objValue.value.linkwork2
  ) {
    lxfs.value.push({
      index: 2,
      name: objValue.value.ceContactname2,
      work: objValue.value.linkwork2,
      phone: objValue.value.ceContactmobile2
    })
  }
  if (
    objValue.value.ceContactname3 ||
    objValue.value.ceContactmobile3 ||
    objValue.value.linkwork3
  ) {
    lxfs.value.push({
      index: 3,
      name: objValue.value.ceContactname3,
      work: objValue.value.linkwork3,
      phone: objValue.value.ceContactmobile3
    })
  }
  await mealList()
  await customerList()

  await fetchManager()
  await fetchAgency()
  await fetchTaxBureau()
  await fetchRegion()
  await fetchCity()
  await getMaterialList()
}
init()

// 查询套餐列表
async function mealList() {
  let sendData = {
    pageNum: 1,
    pageSize: 10000
  }

  const res = await listTable(proxy.addDateRange(sendData))
  if (res.code === 200) {
    tableList.value = res.rows
  } else {
    // this.$message.error("获取套餐名称列表失败");
    proxy.$modal.msgError('获取套餐名称列表失败！')
  }
}
async function getDetail() {
  let res = null
  // 获取订单详情（订单管理入口）
  if (route.currentRoute.value.query.id) {
    res = await detailOrder({ id: route.currentRoute.value.query.id })
    if (res.code === 200) {
      objValue.value = { ...res.data.customer, ...res.data.order, ...res.data }
      objValue.value.orderlineList = res.data.orderlinePage
        ? res.data.orderlinePage.rows
        : []
    }
  }
  // 获取客户详情（客户档案入口）
  if (route.currentRoute.value.query.cusId) {
    res = await fetchCustomerDetail(route.currentRoute.value.query.cusId)
    if (res.code === 200) objValue.value = { ...objValue.value, ...res.data }
    console.log('客户详情', objValue.value)
  }
}

async function customerList() {
  const res = await customerListSelect()
  if (res.code === 200) {
    option.value.ceEtpname = res.data
    // console.log(option.value.ceEtpname);
  } else {
    // this.$message.error("获取企业客户下拉列表失败");
    proxy.$modal.msgError('获取企业客户下拉列表失败')
  }
}

async function fetchManager() {
  const res = await fetchManagerList()
  if (res.code === 200) {
    option.value.salespersonId = res.data.map(item => ({
      ...item,
      khjlName: `${item.khjlName} (${item.khjlId})`
    }))
    option.value.khjlid = res.data.map(item => ({
      ...item,
      khjlName: `${item.khjlName} (${item.khjlId})`
    }))
  } else {
    // this.$message.error("获取客户经理列表失败");
    proxy.$modal.msgError('获取客户经理列表失败')
  }
}

async function fetchAgency() {
  const res = await fetchAgencyList()
  if (res.code === 200) {
    option.value.dzjgId = res.data
  } else {
    // this.$message.error("获取代账机构列表失败");
    proxy.$modal.msgError('获取代账机构列表失败')
  }
}

async function fetchTaxBureau() {
  const res = await fetchCustomerTaxBureauList()
  if (res.code === 200) {
    option.value.ceTaxbureaid = res.data
  } else {
    // this.$message.error("获取税局列表失败");
    proxy.$modal.msgError('获取税局列表失败')
  }
}

async function fetchRegion() {
  const res = await fetchRegionList()
  if (res.code === 200) {
    option.value.region = res.data
  } else {
    // this.$message.error("获取区域列表失败");
    proxy.$modal.msgError('获取区域列表失败')
  }
}

async function fetchCity() {
  const res = await fetchCityList()
  if (res.code === 200) {
    option.value.citycodes = res.data
  } else {
    // this.$message.error("获取城市列表失败");
    proxy.$modal.msgError('获取城市列表失败')
  }
}

/**返回 */
function handleBack() {
  if (route.currentRoute.value.query.mark == 'myOrder') {
    router.push({ path: '/xs/ddgl/myOrder', query: {} })
  } else if (route.currentRoute.value.query.mark == 'pending') {
    router.push({ path: '/xs/ddgl/audit', query: { mark: 'pending' } })
  } else if (route.currentRoute.value.query.mark == 'audited') {
    router.push({ path: '/xs/ddgl/audit', query: { mark: 'audited' } })
  } else {
    router.push({ path: '/xs/khda', query: {} })
  }

  // route.currentRoute.value.query.id
  //     ? router.push({ path: "/xs/ddgl/myOrder", query: {} })
  //     : router.push({ path: "/xs/khda", query: {} });
}

/**提交 */
async function handleSubmit(flag) {
  let baseValid = true,
    contactValid = true,
    agencyValid = true,
    lxfsValid = true,
    invoiceValid = true,
    baseOrderValid = true
  if (route.currentRoute.value.query.id) {
    proxy.$refs.baseOrder.$refs.form.validate(valid => {
      if (!valid) {
        baseOrderValid = false
      }
    })

    proxy.$refs.invoice.$refs.form.validate(valid => {
      if (!valid) {
        invoiceValid = false
      }
    })
  } else {
    // 代账公司专属信息
    if (objValue.value.custype === '1') {
      proxy.$refs.agency.$refs.form.validate(valid => {
        if (!valid) {
          agencyValid = false
        }
      })
    }
    // 客户信息
    proxy.$refs.base.$refs.form.validate(valid => {
      if (!valid) {
        baseValid = false
      }
    })
    // 联系方式
    proxy.$refs.contact.$refs.form.validate(valid => {
      if (!valid) {
        contactValid = false
      }
    })

    // 联系方式表格数据
    for (const item of lxfs.value) {
      if (item.index != 3 && !item.name) {
        // this.$message.warning(`联系人${item.index}名称不能为空`);
        proxy.$message({
          message: `联系人${item.index}名称不能为空`,
          type: 'warning'
        })
        lxfsValid = false
      } else if (item.index == 1 && !item.work) {
        // this.$message.warning(`联系人${item.index}职务不能为空`);
        proxy.$message({
          message: `联系人${item.index}职务不能为空`,
          type: 'warning'
        })
        lxfsValid = false
      } else if (!item.phone) {
        // this.$message.warning(`联系人${item.index}联系电话不能为空`);
        proxy.$message({
          message: `联系人${item.index}联系电话不能为空`,
          type: 'warning'
        })
        lxfsValid = false
      }
    }
  }

  if (
    baseValid &&
    contactValid &&
    agencyValid &&
    lxfsValid &&
    baseOrderValid &&
    invoiceValid
  ) {
    if (flag == -1) {
      // 数量跟金额变成负数
      objValue.value.orderlineList.forEach(item => {
        item.matNum *= -1
        item.amount *= -1
      })
    }

    const data = objValue.value
    data.ceContactname = lxfs.value[0].name
    data.ceContactmobileOne = lxfs.value[0].phone
    data.linkwork = lxfs.value[0].work

    data.ceContactname2 = lxfs.value[1]?.name || null
    data.ceContactmobile2 = lxfs.value[1]?.phone || null
    data.linkwork2 = lxfs.value[1]?.work || null

    data.ceContactname3 = lxfs.value[2]?.name || null
    data.ceContactmobile3 = lxfs.value[2]?.phone || null
    data.linkwork3 = lxfs.value[2]?.work || null
    loading.value = true
    try {
      // 客户档案入口
      if (route.currentRoute.value.query.cusId) {
        let res = await updateCompany(data)
        if (res.code === 200) {
          // this.$message.success("操作成功");
          proxy.$modal.msgSuccess('操作成功')
          router.push({ path: '/xs/khda' })
        } else proxy.$modal.msgError(res.msg)
        loading.value = false
      } // 订单管理入口
      if (route.currentRoute.value.query.id) {
        // 保存、复制订单、红字订单 按钮

        let res
        if (flag == -1 || flag == 1) res = await addOrder(data)
        else res = await updateOrder(data)
        if (res.code === 200) {
          // this.$message.success("操作成功");
          proxy.$modal.msgSuccess('操作成功')
          if (route.currentRoute.value.query.mark == 'myOrder') {
            router.push({ path: '/xs/ddgl/myOrder', query: {} })
          } else if (route.currentRoute.value.query.mark == 'pending') {
            router.push({ path: '/xs/ddgl/audit', query: {} })
          } else if (route.currentRoute.value.query.mark == 'audited') {
            router.push({ path: '/xs/ddgl/audit', query: {} })
          }
        } else proxy.$modal.msgError(res.msg)
        loading.value = false
      }
    } catch (e) {
      console.log(e)
      // this.$message.error("修改订单服务异常 请重试");
      proxy.$modal.msgError('修改订单服务异常 请重试')
      loading.value = false
    }
  }
}

/**添加联系方式 */
function addLxfs() {
  lxfs.value.push({
    index: lxfs.value.length + 1,
    name: '',
    work: '',
    phone: ''
  })
}

/**删除联系方式 */
function delLxfs(index) {
  lxfs.value.splice(index - 1, 1)
  lxfs.value = lxfs.value.map((item, index) => ({
    ...item,
    index: index + 1
  }))
}

// 新增合同
function addAgreement(e) {
  agreementDialogVisible.value = true
  console.log('agreementDialogVisible', agreementDialogVisible.value)
  agreementDialogTitle.value = '新增合同'
}
// 删除合同
function deleteAgreements(e) {
  let that = this
  // 确定删除么
  proxy
    .$confirm('是否确认删除?', '警告', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    .then(function () {
      for (var i in urls.value) {
        var index = objValue.value.fileList.findIndex(item => {
          if (item.url == urls.value[i]) return true
        })
        objValue.value.fileList.splice(index, 1)
      }
      // that.msgSuccess("删除成功");
      proxy.$modal.msgSuccess('删除成功')
    })
}

// 多选框选中数据
function handleSelectionChangeTwo(selection) {
  urls.value = selection.map(item => item.url)
  console.log(urls.value)
  single.value = selection.length != 1
  multiple.value = !selection.length
}

/** 下载模板操作 */
function fetchFile(url) {
  // console.log(process.env.VUE_APP_BASE_API)
  window.location.href = url
}

// 新增物品
function addGoods(e) {
  dialogVisible.value = true
  dialogTitle.value = '新增物品'
  resetFormT()
  resetMealFormT()
}

function resetFormT() {
  formT.value = {
    matId: '',
    amount: '',
    unitPrice: '',
    matNum: '',
    unitName: '',
    matType: '',
    matName: '',
    remark: ''
  }
}

// 删除物品
function deleteGoods(e) {
  let that = this
  // 确定删除么
  proxy
    .$confirm(
      '是否确认删除物品编码为"' + matCodes.value + '"的数据项?',
      '警告',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    .then(function () {
      for (var i in matCodes.value) {
        var index = objValue.value.orderlineList.findIndex(item => {
          if (item.matId == matCodes.value[i]) return true
        })
        objValue.value.orderlineList.splice(index, 1)
      }
      // that.msgSuccess("删除成功");
      proxy.$modal.msgSuccess('删除成功')
    })
}

// 修改物品
function updateGoods(e) {
  dialogVisible.value = true
  dialogTitle.value = '修改物品'
  let that = this
  objValue.value.orderlineList.forEach(item => {
    if (item.matId == matCodes.value[0]) {
      formT.value = item
    }
  })
}

function onInput(flag) {
  if (formT.value.amount) {
    if (flag == 0 && formT.value.matNum) {
      formT.value.unitPrice =
        parseFloat(formT.value.amount) / parseFloat(formT.value.matNum)
    } else if (flag == 1 && formT.value.unitPrice) {
      formT.value.matNum =
        parseFloat(formT.value.amount) / parseFloat(formT.value.unitPrice)
    }
  }
}

// 多选框选中数据
function handleSelectionChange(selection) {
  matCodes.value = selection.map(item => item.matId)
  console.log(matCodes.value)
  console.log('checkStatus===>', route.currentRoute.value)
  if (route.currentRoute.value.query.checkStatus != '2') {
    single.value = selection.length != 1
    multiple2.value = !selection.length
  }
}

function agreementOnConfirm() {
  proxy.$refs.agreementFormRef.validate(valid => {
    if (valid) {
      if (agreementForm.value.url == null) {
        // this.$message("请上传合同");
        proxy.$message({
          message: '请上传合同',
          type: 'warning'
        })
        return false
      }
      objValue.value.fileList.push(agreementForm.value)
      agreementForm.value = { fileName: null, url: null }
      agreementDialogVisible.value = false
    }
  })
}

// 覆盖默认的上传行为
async function requestUpload(file) {
  let formData = new FormData()
  formData.append('file', file.file)
  try {
    const res = await fileUpload(formData)
    if (res.code === 200) {
      console.log('res.url:' + res.data.name)
      agreementForm.value.url = res.data.url
    } else {
      console.log('res===', res)
      // this.$message.error(res.msg);
      proxy.$modal.msgError('上传失败!')
    }
  } catch (e) {
    console.log(e)
  }
}

function matCodeChange(e) {
  console.log(e)
  for (var i in matCodeOptions.value) {
    if (e == matCodeOptions.value[i].matCode) {
      formT.value.matName = matCodeOptions.value[i].matName
      formT.value.matType = matCodeOptions.value[i].spec
      formT.value.unitName = matCodeOptions.value[i].unit
    }
  }
}

function matNameChange(e) {
  console.log(e)
  for (var i in matCodeOptions.value) {
    if (e == matCodeOptions.value[i].matName) {
      formT.value.matId = matCodeOptions.value[i].matCode
      formT.value.matType = matCodeOptions.value[i].spec
      formT.value.unitName = matCodeOptions.value[i].unit
    }
  }
}

async function getMaterialList() {
  const res = await materialList({ istatue: 1 })
  if (res.code === 200) {
    matCodeOptions.value = res.rows
  } else {
    // this.$message.error("获取物料列表失败！");
    proxy.$modal.msgError('获取物料列表失败！')
  }
}

function mealNameChange(e) {
  console.log(e)
  for (var i in tableList.value) {
    if (e == tableList.value[i].id) {
      formMeal.value.amount = tableList.value[i].amount
      getMealLineList({ mealId: e }).then(res => {
        if (res.code == 200) {
          mealLines.value = res.data
        } else proxy.$modal.msgError(res.msg)
      })
      break
    }
  }
}

// 确定按钮
function onConfirm() {
  proxy.$refs['queryForm'].validate(valid => {
    console.log('valid:' + valid)
    if (valid) {
      if (dialogTitle.value == '新增物品') {
        objValue.value.orderlineList.push(formT.value)
      } else if (dialogTitle.value == '修改物品') {
      }
      resetFormT()
      dialogVisible.value = false
    }
  })
}

// 确定按钮
function onConfirmMeal() {
  proxy.$refs['mealForm'].validate(valid => {
    console.log('valid:' + valid)
    if (valid) {
      if (dialogTitle.value == '新增物品') {
        console.log(mealLines.value)
        for (var i = 0; i < mealLines.value.length; i++) {
          var mealFormT = {
            matId: mealLines.value[i].matCode,
            matType: mealLines.value[i].spec,
            amount: mealLines.value[i].amount,
            unitPrice: mealLines.value[i].price,
            matNum: mealLines.value[i].matNum,
            unitName: mealLines.value[i].unit,
            matName: mealLines.value[i].matName
          }
          objValue.value.orderlineList.push(mealFormT)
        }
      } else if (dialogTitle.value == '修改物品') {
      }
      resetMealFormT()
      dialogVisible.value = false
    }
  })
}

function resetMealFormT() {
  mealLines.value = []
  formMeal.value = {
    mealName: '',
    amount: ''
  }
}

/** 作废订单 */
function handleCancel() {
  loadingCancel.value = true
  let ids = []
  ids.push(route.currentRoute.value.query.id)
  cancelOrder({ ids }).then(res => {
    if (res.code === 200) {
      // this.$message.success("操作成功");
      proxy.$modal.msgSuccess('操作成功')
    } else proxy.$modal.msgError(res.msg)
    loadingCancel.value = false
    router.push({ path: '/xs/ddgl/ddlb' })
  })
}

/** 复制生成订单 */
function handleCopy() {
  loadingCopy.value = true

  copyOrder({ id: route.currentRoute.value.query.id }).then(res => {
    if (res.code === 200) {
      // this.$message.success("操作成功");
      proxy.$modal.msgSuccess('操作成功')
    } else proxy.$modal.msgError(res.msg)
    loadingCopy.value = false
    if (route.currentRoute.value.query.mark == 'pending') {
      router.push({ path: '/xs/ddgl/audit', query: {} })
    } else if (route.currentRoute.value.query.mark == 'audited') {
      router.push({ path: '/xs/ddgl/audit', query: {} })
    }
    // router.push({ path: "/xs/ddgl/ddlb" });
  })
}

/**生成红字订单 */
function handleRedCreate() {
  loadingRedCreate.value = true

  createRedOrder({ id: route.currentRoute.value.query.id }).then(res => {
    if (res.code === 200) {
      // this.$message.success("操作成功");
      proxy.$modal.msgSuccess('操作成功')
    } else proxy.$modal.msgError(res.msg)
    loadingRedCreate.value = false
    if (route.currentRoute.value.query.mark == 'audited') {
      router.push({ path: '/xs/ddgl/audit', query: {} })
    }
  })
}

/**审核订单 */
function handleCheck(checkStatus) {
  if (checkStatus == 2)
    //通过
    proxy.$refs.ordernoT.$refs.form.validate(valid => {
      if (valid) {
        console.log(ordernoValue.value)
        loadingCheck.value = true
        checkOrder({
          checkStatus,
          id: route.currentRoute.value.query.id,
          orderNo: ordernoValue.value.orderNo
        }).then(res => {
          if (res.code === 200) {
            // this.$message.success("操作成功");
            proxy.$modal.msgSuccess('操作成功')
          } else proxy.$modal.msgError(res.msg)
          loadingCheck.value = false
          if (route.currentRoute.value.query.mark == 'pending') {
            router.push({ path: '/xs/ddgl/audit', query: {} })
          }
        })
      }
    })
  else if (checkStatus == 7) {
    //不通过
    loadingNoCheck.value = true
    checkOrder({
      checkStatus,
      id: route.currentRoute.value.query.id
    }).then(res => {
      if (res.code === 200) {
        // this.$message.success("操作成功");
        proxy.$modal.msgSuccess('操作成功')
      } else proxy.$modal.msgError(res.msg)
      loadingNoCheck.value = false
      if (route.currentRoute.value.query.mark == 'pending') {
        router.push({ path: '/xs/ddgl/audit', query: {} })
      }
    })
  }
}

function onchangeT(e) {
  console.log(e)
  objValue.value.ceTaxcode = e
}
</script>

<style scoped lang="scss">
.page {
  min-height: calc(100vh - 89px);
  height: calc(100vh - 89px);

  .page-wrapper {
    height: 100%;
    padding: 20px 60px;
    overflow-y: scroll;
  }
}

.el-collapse {
  margin-bottom: 40px;
}

.header {
  text-align: center;
  font-weight: 600;
  font-size: 18px;
  margin-bottom: 20px;
  height: 50px;
  line-height: 50px;
}

.collapse-title {
  font-weight: 600;
}

.block {
  width: 3px;
  display: inline-block;
  height: 16px;
  background-color: rgb(62, 146, 255);
  margin-right: 8px;
}

.col .item {
  height: 36px;
  margin-bottom: 20px;
}

.collapse .row:last-child {
  margin-bottom: 10px;
}

.item-label,
.item-value {
  font-size: 12px;
  line-height: 30px;
}

.item-label {
  text-align: right;
  line-height: 36px;
  margin-right: 15px;
}

.footer {
  width: 100%;
  background-color: white;
  // text-align: right;
  padding: 10px 30px;
  position: absolute;
  left: 0;
  z-index: 9999;
  right: 0;
  bottom: 0;
  height: 55px;
  border-top: 1px solid lightgray;
  display: flex;
  justify-content: space-around;

  .el-button + .el-button {
    margin-left: 20px;
  }

  // .el-button {
  //   width: 100px;
  // }
}

.table {
  margin: 22px 0;

  .table-label {
    display: inline-block;
    width: 200px;
    text-align: right;
    line-height: 36px;
    padding-right: 12px;
    font-size: 14px;
    color: #606266;
    font-weight: 700;
    vertical-align: top;
  }

  .table-content {
    width: calc(100% - 200px);
    display: inline-block;
  }
}
</style>

<style>
.el-timeline-item .el-timeline-item__wrapper {
  padding-left: 0px;
  top: 20px;
  width: 130px;
}

.el-timeline-item {
  float: left;
}

.el-timeline-item .el-timeline-item__tail {
  top: 5px;
  height: 2px;
  border: none;
  width: 130px;
  background: #dfe4ed;
}

.footer {
  z-index: 999 !important;
}
</style>
